/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package daos;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author mpastarini
 */
public class MSSQLDao {

    private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private static final String USER   = "sa";
    private static final String PASSWD = "zxc";
    private static final String URL    = "jdbc:sqlserver://localhost:1433;databaseName=dbPortal";

    private Connection        conn;
    private CallableStatement cstmt;

    protected MSSQLDao() throws Exception
    {        
        try {            
            Class.forName(MSSQLDao.DRIVER).newInstance();
            this.conn = DriverManager.getConnection(MSSQLDao.URL, MSSQLDao.USER, MSSQLDao.PASSWD);
            this.conn.setAutoCommit(true);
           
        }
        catch(InstantiationException e1) 
        {
            System.out.println("Error  Conexion "+ e1);
            throw new Exception("Conexion: " + e1.getMessage());
        } 
        catch(IllegalAccessException e2) 
        {
            
            throw new Exception("Conexion: " + e2.getMessage());
        }        
        catch(ClassNotFoundException e3)
        {
            System.out.println("No encontro la clase  "+ e3);
            throw new Exception("Conexion: " + e3.getMessage());
        }
        catch(SQLException e4)
        {
            System.out.println("SQL ERROR \n "+ e4);
            throw new Exception ("Conexion: " + e4.getMessage());
        }
    }
    
    protected Connection getConnection() {
        return this.conn;        
    }        

    protected void setStatement(String stmt) throws Exception {
        try{    
            this.cstmt = this.conn.prepareCall("{ CALL " + stmt + " }");
        } catch(SQLException ex) {
            throw new Exception(ex.getMessage());
        }    
    }        

    protected CallableStatement getStatement() {
        return this.cstmt;
    }        

    protected void destroy()    {
        try {
            if(this.cstmt != null) {
                this.cstmt.close();
            }

            if(this.conn != null) {
                this.conn.close();
            }
        } catch(SQLException ex) { }
    }

}
